# -*- coding: utf-8 -*-
'''
Created on 2011-8-21

@author: zxz
'''

from flask import Flask, session, request

from datasource import db_session

from app import app
from commentsModel import Comments
from common.jsonUtil import success, error
from forms import CommentsForm

from datetime import datetime

MAX_SIZE = 50

@app.route('/comments/', methods=['GET'])
def comments_test():
    return success({'comments' : 'comments test'})

@app.route('/comments/<int:sid>/<int:offset>/<int:size>/', methods=['GET'])
def comments_list(sid, offset, size):
    ''' 查询 '''
    if size < 1 or size > MAX_SIZE or offset < 0:
        return error('610', u'请求参数错误')
    comments = db_session.query(Comments).filter(Comments.sid == sid).order_by(Comments.gmt_create.desc()).offset(offset).limit(size)
    commentEntrys = [c.entry() for c in comments]
    return success({'comments':commentEntrys})

@app.route('/comments/count/<int:sid>/', methods=['GET'])
def comments_count(sid):
    ''' 查询 '''
    count = db_session.query(Comments).filter(Comments.sid == sid).count()
    return success({'count':count})

@app.route('/comments/add/', methods=['POST'])
def comments_add():
    ''' 回复 sid、content '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'没有权限')
    form = CommentsForm(request.form)
    if not form.validate():
        return error('701', u'输入参数错误')
    comment = Comments(form.sid.data, uid, form.content.data, datetime.now())
    db_session.add(comment)
    db_session.commit()
    return success({'comment':comment.entity()})

@app.route('/comments/r/<int:id>/', methods=['GET'])
def comments_remove(id):
    uid = session.get('uid')
    if not uid:
        return error('500', u'没有权限')
    comments = db_session.query(Comments).filter(Comments.id == id).filter(Comments.uid == uid).all()
    for c in comments:
        db_session.delete(c)
        db_session.commit()
    return success()

